"""
ComfyUI Dify Integration Debug Helper
调试工具，帮助诊断ComfyUI与Dify集成的问题
"""

import json
import logging
import sys
from typing import Dict, Any, List, Optional
from datetime import datetime

# 设置日志
logging.basicConfig(
    level=logging.INFO,
    format='[%(asctime)s] %(levelname)s - %(message)s',
    datefmt='%Y-%m-%d %H:%M:%S'
)
logger = logging.getLogger(__name__)

class DifyIntegrationDebugger:
    """Dify集成调试器"""
    
    def __init__(self):
        self.checks_passed = 0
        self.checks_failed = 0
        self.warnings = []
        self.errors = []
        
    def run_all_checks(self) -> Dict[str, Any]:
        """运行所有诊断检查"""
        logger.info("开始运行 Dify 集成诊断检查...")
        
        results = {
            "timestamp": datetime.now().isoformat(),
            "checks": {},
            "summary": {},
            "recommendations": []
        }
        
        # 运行各项检查
        checks = [
            ("节点加载检查", self.check_node_loading),
            ("输出格式检查", self.check_output_format),
            ("JSON 格式验证", self.check_json_format),
            ("编码支持检查", self.check_encoding_support),
            ("API 处理器检查", self.check_api_handler),
            ("Dify 格式兼容性检查", self.check_dify_compatibility)
        ]
        
        for check_name, check_func in checks:
            try:
                logger.info(f"执行检查: {check_name}")
                result = check_func()
                results["checks"][check_name] = result
                
                if result["status"] == "passed":
                    self.checks_passed += 1
                elif result["status"] == "failed":
                    self.checks_failed += 1
                    self.errors.append(f"{check_name}: {result['message']}")
                elif result["status"] == "warning":
                    self.warnings.append(f"{check_name}: {result['message']}")
                    
            except Exception as e:
                logger.error(f"检查 {check_name} 时出错: {str(e)}")
                results["checks"][check_name] = {
                    "status": "error",
                    "message": str(e)
                }
                self.checks_failed += 1
                self.errors.append(f"{check_name}: 执行时出错 - {str(e)}")
        
        # 生成总结和建议
        results["summary"] = self._generate_summary()
        results["recommendations"] = self._generate_recommendations()
        
        return results
    
    def check_node_loading(self) -> Dict[str, Any]:
        """检查节点是否正确加载"""
        try:
            from text_output_node import NODE_CLASS_MAPPINGS, NODE_DISPLAY_NAME_MAPPINGS
            
            expected_nodes = ["DifyTextOutputNode", "TextDisplayNode", "TextCombineNode"]
            loaded_nodes = list(NODE_CLASS_MAPPINGS.keys())
            
            missing_nodes = [node for node in expected_nodes if node not in loaded_nodes]
            
            if missing_nodes:
                return {
                    "status": "failed",
                    "message": f"缺少节点: {missing_nodes}",
                    "details": {
                        "expected": expected_nodes,
                        "loaded": loaded_nodes,
                        "missing": missing_nodes
                    }
                }
            
            return {
                "status": "passed",
                "message": f"成功加载所有 {len(loaded_nodes)} 个节点",
                "details": {
                    "loaded_nodes": loaded_nodes
                }
            }
            
        except ImportError as e:
            return {
                "status": "failed",
                "message": f"无法导入节点模块: {str(e)}",
                "details": {"import_error": str(e)}
            }
    
    def check_output_format(self) -> Dict[str, Any]:
        """检查输出格式是否正确"""
        try:
            from text_output_node import DifyTextOutputNode
            
            # 创建节点实例并测试
            node = DifyTextOutputNode()
            test_text = "测试文本内容"
            
            formatted_output, json_output = node.process_text_output(
                text=test_text,
                format_for_dify=True,
                include_metadata=False,
                additional_data="[]"
            )
            
            # 验证输出格式
            if not isinstance(json_output, dict):
                return {
                    "status": "failed",
                    "message": "JSON输出不是字典格式",
                    "details": {"output_type": type(json_output).__name__}
                }
            
            required_fields = ["text", "files", "json"]
            missing_fields = [field for field in required_fields if field not in json_output]
            
            if missing_fields:
                return {
                    "status": "failed",
                    "message": f"输出缺少必需字段: {missing_fields}",
                    "details": {
                        "required": required_fields,
                        "present": list(json_output.keys()),
                        "missing": missing_fields
                    }
                }
            
            return {
                "status": "passed",
                "message": "输出格式检查通过",
                "details": {
                    "output_structure": {
                        "text": type(json_output["text"]).__name__,
                        "files": type(json_output["files"]).__name__,
                        "json": type(json_output["json"]).__name__
                    }
                }
            }
            
        except Exception as e:
            return {
                "status": "failed",
                "message": f"输出格式检查失败: {str(e)}",
                "details": {"error": str(e)}
            }
    
    def check_json_format(self) -> Dict[str, Any]:
        """检查JSON格式是否有效"""
        try:
            from text_output_node import DifyTextOutputNode
            
            node = DifyTextOutputNode()
            test_cases = [
                ("基础文本", "简单的测试文本", "[]"),
                ("中文内容", "这是中文测试内容", "[]"),
                ("带元数据", "测试内容", '[{"key": "value"}]'),
                ("特殊字符", "包含特殊字符: !@#$%^&*()", "[]")
            ]
            
            for test_name, text, additional_data in test_cases:
                formatted_output, json_output = node.process_text_output(
                    text=text,
                    format_for_dify=True,
                    additional_data=additional_data
                )
                
                # 验证能否解析为JSON
                try:
                    parsed = json.loads(formatted_output)
                    if parsed != json_output:
                        return {
                            "status": "warning",
                            "message": f"JSON序列化不一致: {test_name}",
                            "details": {"test_case": test_name}
                        }
                except json.JSONDecodeError as e:
                    return {
                        "status": "failed",
                        "message": f"JSON格式无效: {test_name} - {str(e)}",
                        "details": {"test_case": test_name, "json_error": str(e)}
                    }
            
            return {
                "status": "passed",
                "message": f"所有 {len(test_cases)} 个JSON格式测试通过",
                "details": {"test_cases": len(test_cases)}
            }
            
        except Exception as e:
            return {
                "status": "failed",
                "message": f"JSON格式检查失败: {str(e)}",
                "details": {"error": str(e)}
            }
    
    def check_encoding_support(self) -> Dict[str, Any]:
        """检查编码支持"""
        try:
            from text_output_node import DifyTextOutputNode
            
            node = DifyTextOutputNode()
            
            # 测试各种编码的文本
            test_texts = [
                "English text",
                "中文文本测试",
                "日本語テスト",
                "한국어 테스트",
                "Русский текст",
                "العربية",
                "🎉 Emoji test 🚀"
            ]
            
            for text in test_texts:
                formatted_output, json_output = node.process_text_output(text=text)
                
                # 验证文本是否正确保存和解析
                if json_output["text"] != text:
                    return {
                        "status": "failed",
                        "message": f"编码处理失败，文本不匹配: {text}",
                        "details": {
                            "original": text,
                            "processed": json_output["text"]
                        }
                    }
            
            return {
                "status": "passed",
                "message": f"编码支持检查通过，测试了 {len(test_texts)} 种语言/字符",
                "details": {"tested_languages": len(test_texts)}
            }
            
        except Exception as e:
            return {
                "status": "failed",
                "message": f"编码支持检查失败: {str(e)}",
                "details": {"error": str(e)}
            }
    
    def check_api_handler(self) -> Dict[str, Any]:
        """检查API处理器"""
        try:
            from api_handler import DifyAPIHandler, format_for_dify
            
            handler = DifyAPIHandler()
            
            # 测试格式化功能
            test_data = "测试数据"
            result = format_for_dify(test_data, "text")
            
            # 验证结果格式
            if not isinstance(result, dict) or "text" not in result:
                return {
                    "status": "failed",
                    "message": "API处理器返回格式不正确",
                    "details": {"result_type": type(result).__name__}
                }
            
            # 验证格式
            if not handler.validate_dify_format(result):
                return {
                    "status": "failed",
                    "message": "API处理器生成的格式不符合Dify要求",
                    "details": {"result": result}
                }
            
            return {
                "status": "passed",
                "message": "API处理器功能正常",
                "details": {"handler_class": "DifyAPIHandler"}
            }
            
        except ImportError:
            return {
                "status": "warning",
                "message": "API处理器模块未找到，功能可能受限",
                "details": {"module": "api_handler"}
            }
        except Exception as e:
            return {
                "status": "failed",
                "message": f"API处理器检查失败: {str(e)}",
                "details": {"error": str(e)}
            }
    
    def check_dify_compatibility(self) -> Dict[str, Any]:
        """检查Dify兼容性"""
        try:
            from text_output_node import DifyTextOutputNode
            
            node = DifyTextOutputNode()
            
            # 生成标准的Dify格式输出
            formatted_output, json_output = node.process_text_output(
                text="Dify兼容性测试",
                format_for_dify=True,
                include_metadata=True,
                additional_data='[{"test": "data"}]'
            )
            
            # 检查必需的Dify格式要求
            compatibility_checks = [
                ("包含text字段", "text" in json_output and isinstance(json_output["text"], str)),
                ("包含files字段", "files" in json_output and isinstance(json_output["files"], list)),
                ("包含json字段", "json" in json_output and isinstance(json_output["json"], list)),
                ("json字段有data", len(json_output["json"]) > 0 and "data" in json_output["json"][0]),
                ("输出可序列化", self._test_json_serializable(json_output))
            ]
            
            failed_checks = [check for check, result in compatibility_checks if not result]
            
            if failed_checks:
                return {
                    "status": "failed",
                    "message": f"Dify兼容性检查失败: {failed_checks}",
                    "details": {
                        "failed_checks": failed_checks,
                        "output_sample": json_output
                    }
                }
            
            return {
                "status": "passed",
                "message": "Dify兼容性检查通过",
                "details": {
                    "checks_passed": len(compatibility_checks),
                    "output_sample": json_output
                }
            }
            
        except Exception as e:
            return {
                "status": "failed",
                "message": f"Dify兼容性检查失败: {str(e)}",
                "details": {"error": str(e)}
            }
    
    def _test_json_serializable(self, data: Any) -> bool:
        """测试数据是否可以JSON序列化"""
        try:
            json.dumps(data, ensure_ascii=False)
            return True
        except (TypeError, ValueError):
            return False
    
    def _generate_summary(self) -> Dict[str, Any]:
        """生成检查总结"""
        total_checks = self.checks_passed + self.checks_failed
        
        return {
            "total_checks": total_checks,
            "passed": self.checks_passed,
            "failed": self.checks_failed,
            "warnings": len(self.warnings),
            "success_rate": (self.checks_passed / total_checks * 100) if total_checks > 0 else 0,
            "status": "healthy" if self.checks_failed == 0 else "has_issues"
        }
    
    def _generate_recommendations(self) -> List[str]:
        """生成修复建议"""
        recommendations = []
        
        if self.checks_failed > 0:
            recommendations.append("存在严重问题，请查看具体错误信息并修复")
        
        if len(self.warnings) > 0:
            recommendations.append("存在警告，建议检查相关配置")
        
        if "节点加载检查" in [error.split(":")[0] for error in self.errors]:
            recommendations.extend([
                "1. 确认所有文件已正确复制到 custom_nodes 目录",
                "2. 检查文件权限是否正确",
                "3. 重启 ComfyUI"
            ])
        
        if "输出格式检查" in [error.split(":")[0] for error in self.errors]:
            recommendations.extend([
                "1. 检查节点实现是否正确",
                "2. 验证输出格式是否符合预期",
                "3. 查看 ComfyUI 控制台日志"
            ])
        
        if "Dify兼容性检查" in [error.split(":")[0] for error in self.errors]:
            recommendations.extend([
                "1. 确认输出格式完全符合 Dify 要求",
                "2. 检查 JSON 结构是否正确",
                "3. 测试在 Dify 中的实际使用"
            ])
        
        if not recommendations:
            recommendations.append("所有检查通过！您的 Dify 集成配置正常。")
        
        return recommendations

def run_debug():
    """运行调试检查的主函数"""
    debugger = DifyIntegrationDebugger()
    results = debugger.run_all_checks()
    
    # 打印结果
    print("\n" + "="*60)
    print("ComfyUI Dify Integration 诊断结果")
    print("="*60)
    
    summary = results["summary"]
    print(f"\n📊 总结:")
    print(f"  - 总检查项: {summary['total_checks']}")
    print(f"  - 通过: {summary['passed']}")
    print(f"  - 失败: {summary['failed']}")
    print(f"  - 警告: {summary['warnings']}")
    print(f"  - 成功率: {summary['success_rate']:.1f}%")
    print(f"  - 状态: {'✅ 健康' if summary['status'] == 'healthy' else '⚠️ 有问题'}")
    
    print(f"\n🔍 详细检查结果:")
    for check_name, result in results["checks"].items():
        status_icon = {"passed": "✅", "failed": "❌", "warning": "⚠️", "error": "🚫"}.get(result["status"], "❓")
        print(f"  {status_icon} {check_name}: {result['message']}")
    
    if results["recommendations"]:
        print(f"\n💡 建议:")
        for i, rec in enumerate(results["recommendations"], 1):
            print(f"  {i}. {rec}")
    
    print("\n" + "="*60)
    
    return results

if __name__ == "__main__":
    # 如果直接运行此文件，执行调试检查
    run_debug() 